package handlers

import (
	"awesome-devops/applications/backend/modules/requests"
	"awesome-devops/applications/backend/modules/services"
	"awesome-devops/applications/tools"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
	"reflect"
)

type WebHookHandler struct {
	awesomehttp.HttpBaseHandler
}

func (handler *WebHookHandler) GetModuleName() string {
	return "/webhook"
}

func (handler *WebHookHandler) ActionIndex() string {
	accessToken := requests.Input(handler.HttpContext, "access_token", reflect.String).(string)
	commitId := requests.Input(handler.HttpContext, "after", reflect.String).(string)
	commit := requests.Input(handler.HttpContext, "commits", reflect.Slice).([]interface{})
	commitLog := commit[0].(map[string]interface{})["message"].(string)
	//tools.GetLogger().Debug(commonhelper.JsonEncode(handler.HttpContext.PostData))
	go func() {
		defer func() {
			if err := recover(); err != nil {
				tools.GetLogger().Error(commonhelper.PrintStackTrace(err))
				return
			}
		}()
		webhook := services.WebHookService{}
		webhook.CreateAutoDeploy(accessToken, commitId, commitLog)
	}()
	return ""
}
